// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package v13;

import com.google.api.adwords.lib.AdWordsService;
import com.google.api.adwords.lib.AdWordsServiceLogger;
import com.google.api.adwords.lib.AdWordsUser;
import com.google.api.adwords.lib.ReportDate;
import com.google.api.adwords.v13.DefinedReportJob;
import com.google.api.adwords.v13.ReportInterface;
import com.google.api.adwords.v13.ReportJobStatus;

/**
 * This demo schedule structure keyword report and retrieves its download URL.
 * To download or retrieve XML automatically, please visit
 * "utils/DownloadReportDemo.java" or "utils/GetReportXmlDemo.java".
 */
public class ReportServiceStructureDemo {
  public static void main(String args[]) throws Exception {
    // Log SOAP XML request and response.
    AdWordsServiceLogger.log();

    // Get AdWordsUser from "~/adwords.properties".
    AdWordsUser user = new AdWordsUser();

    // Get ReportService.
    ReportInterface reportService = user.getService(AdWordsService.V13.REPORT_SERVICE);

    // Create report job.
    DefinedReportJob job = new DefinedReportJob();
    job.setSelectedReportType("Structure");
    job.setAggregationTypes(new String[] {"Keyword"});
    job.setStartDay(new ReportDate(2009, 0, 1).toDate());
    job.setEndDay(new ReportDate(2009, 0, 31).toDate());
    job.setName("Demo Structure Keyword Report");
    job.setSelectedColumns(new String[] {
        "Campaign", "CampaignId", "AdGroup", "AdGroupId", "Keyword",
        "KeywordId", "MaximumCPC"});

    // Validate report job.
    reportService.validateReportJob(job);

    // Schedule report job.
    long jobId = reportService.scheduleReportJob(job);

    // Wait for report to finish.
    ReportJobStatus status = reportService.getReportJobStatus(jobId);
    while (status != ReportJobStatus.Completed && status != ReportJobStatus.Failed) {
      try {
        Thread.sleep(30000);
      } catch (InterruptedException e) {}

      status = reportService.getReportJobStatus(jobId);
      System.out.println("Report job status is " + status.toString());
    }

    if (status == ReportJobStatus.Failed) {
      System.out.println("Job failed!");
    } else {
      System.out.println("The report is ready!");

      // Get report download url.
      String url = reportService.getGzipReportDownloadUrl(jobId);
      System.out.println("Report url is " + url);
    }
  }
}
